package ev.operator;//need to add this line

import ev.data.*;//need to add this line
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/*
 * Pick a subset of genes at random
 * Randomly rearrange the alleles in those positions
 * Note:subset does not have to be contiguous
 */
public class Scramble implements Mutation{

	public Individual mutate(Individual old) {
		int[] list=old.getList();		
		int len=list.length;
		int[] list1=new int[len];
		for(int i=0;i<len;i++){
			list1[i]=list[i];
		}
		//randomly generate the length of subset
		Random r=new Random();
		int lenOfSublist=r.nextInt(len);
		while(lenOfSublist<2){
			lenOfSublist=r.nextInt(len);
		}
		
		//pick the sebset, and subset does not have to be contiguous
		ArrayList<Integer> subList=new ArrayList<Integer>();
		ArrayList<Integer> keepIndex=new ArrayList<Integer>();
		for(int i=0;i<lenOfSublist;i++){
			int p=r.nextInt(lenOfSublist);
			if(!subList.contains(p)){
				subList.add(p);
			}else{
				i--;
			}
			
		}
		for(int i=0;i<lenOfSublist;i++){
			keepIndex.add(subList.get(i));			
		}
		//Randomly rearrange the alleles in those positions
		Collections.shuffle(subList);
		for(int i=0;i<lenOfSublist;i++){
			list[keepIndex.get(i)]=list1[subList.get(i)];
		}
		old.setList(list);
		return old;
	}

}
